package com.jxs.android.sxyw;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;

import com.jxs.android.sxyw.weiget.PopMsg;
import com.jxs.android.sxyw.weiget.TopBar;
import com.jxs.android.util.FileHloder;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;

/**
 * @Des 选择图片
 * @author Jiangxs
 * 
 */
public class SelectPic extends AbstractActivity implements OnItemClickListener {

	private GridView appGridView = null;
	private Context context;
	private List<Bitmap> bitmaps = new ArrayList<Bitmap>();
	private ArrayList<String> fileNames = new ArrayList<String>(5);
	private static int REQUEST_SELECT_PIC = 0x001;
	private static int REQUEST_SELECT_CAMRA = 0x002;
	private int postion = 0;
	private PicAdpter picAdpter;
	private Button submit;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		initTopBar(savedInstanceState, R.layout.select_pic);

		context = this;
		submit = (Button) findViewById(R.id.pic_sumbit);
		appGridView = (GridView) findViewById(R.id.main_app_gridview);
		picAdpter = new PicAdpter(context);
		appGridView.setAdapter(picAdpter);
		appGridView.setOnItemClickListener(this);

		if (null != getIntent()) {
			if (null != getIntent().getExtras()) {
				Bundle bundle = getIntent().getExtras();
				ArrayList<String> reciveredFileNames = bundle.getStringArrayList("fileNames");
				for (int index = 0; index < reciveredFileNames.size(); index++) {
					if (!StringUtils.isEmpety(reciveredFileNames.get(index))) {
						File file = new File(FileHloder.DIR_PIC + reciveredFileNames.get(index));
						if (file.exists() && file.isFile()) {
							bitmaps.add(index, FileHloder.getLocationBitmap(FileHloder.DIR_PIC + reciveredFileNames.get(index)));
							fileNames.add(index, reciveredFileNames.get(index));
						}
					}
				}
			}
		}

		submit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (bitmaps.size() == 1 && picAdpter.getItem(0).equals(bitmaps.get(0))) {
					PopMsg.show("请选择图片...");
				} else {
					handler.sendEmptyMessage(0);
				}
			}
		});
		processAddLocation();
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("fileNames", fileNames);
			intent.putExtras(bundle);
			setResult(RESULT_OK, intent);
			finish();
		}

	};

	private void processAddLocation() {
		bitmaps.add(bitmaps.size(), BitmapFactory.decodeResource(getResources(), R.drawable.icon_album_add));
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		topBar.hindBtn();
		topBar.setTitle("附件照片");
		initTopBarReturn(topBar);
	}

	/**
	 * @Des 点击中间的图片的时候处理事件
	 */

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		toTake(position);
	}

	private void toTake(final int position1) {
		CharSequence[] items = { "相册", "相机" };
		new AlertDialog.Builder(this).setTitle("选择照片").setItems(items, new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				postion = position1;
				if (which == 0) {
					startActivityForResult(StartHelper.getPhotoPickIntent(), REQUEST_SELECT_PIC);
				} else {
					startActivityForResult(StartHelper.getTakePhotoIntent(), REQUEST_SELECT_CAMRA);
				}
			}
		}).create().show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			createPicInfo(data, requestCode);
		}
	}

	private void createPicInfo(Intent data, int requestCode) {
		String fileName = "";
		String cuFileName = System.currentTimeMillis() + ".jpg";
		if (requestCode == REQUEST_SELECT_CAMRA) {
			fileName = FileHloder.DIR_PIC + cuFileName;
			Bitmap photo = data.getParcelableExtra("data");
			FileHloder.savePic(photo, fileName);
		} else if (requestCode == REQUEST_SELECT_PIC) {
			fileName = FileHloder.DIR_PIC + cuFileName;
			Uri uri = data.getData();
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
			int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			if (actualimagecursor.moveToFirst()) {
				String img_path = actualimagecursor.getString(actual_image_column_index);
				try {
					FileHloder.copyFile(new File(img_path), new File(fileName));
				} catch (IOException e) {

				}
			}
		}
		fileNames.add(postion, cuFileName);
		bitmaps.add(postion, FileHloder.getLocationBitmap(fileName));
		picAdpter.notifyDataSetChanged();
		if (postion == 4) {
			bitmaps.remove(5);
			picAdpter.notifyDataSetChanged();
		}
	}

	private class PicAdpter extends BaseAdapter {

		private LayoutInflater inflater = null;

		public PicAdpter(Context context) {
			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return bitmaps.size();
		}

		@Override
		public Bitmap getItem(int position) {
			return bitmaps.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = (ImageView) inflater.inflate(R.layout.img_item, null);
			imageView.setImageBitmap(bitmaps.get(position));
			return imageView;
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

}